package com.android.inestpin.activity.mine;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.inestpin.R;
import com.android.inestpin.app.BaseActivity;
import com.android.inestpin.model.member.SignInData;
import com.android.inestpin.model.member.SignInDataCallback;
import com.android.inestpin.model.member.SignInRCData;
import com.android.inestpin.model.member.SignInRCDataCallback;
import com.android.inestpin.utils.ConstantsUrl;
import com.android.inestpin.utils.HttpUtils;
import com.android.inestpin.utils.MyLog;
import com.android.inestpin.utils.ObjectUtils;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by gao on 2017/10/25.
 */

public class ScoreSignInActivity extends BaseActivity {

    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.listView)
    NestFullListView listView;
    @BindView(R.id.sign_total_score)
    TextView totalScore;
    @BindView(R.id.sign_sign_score)
    TextView signScore;
    @BindView(R.id.sign_consume_score)
    TextView consumeScore;
    @BindView(R.id.sign_now)
    TextView sign_now;

    private Activity mcontext;
    AlertDialog dialog;
    AlertDialog successDialog;
    private boolean networkConnected;
    private boolean isSigned;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_signin);
        mcontext = this;
        ButterKnife.bind(this);
        getData();
    }

    private void getData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERFSIGN;
        MyLog.e("地址", address);
        if (networkConnected) {
            HttpUtils.get(address, null, dataCallback);
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    private String rule;
    SignInRCDataCallback dataCallback = new SignInRCDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(SignInRCData response, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            if (response.getCode() == 0) {
                SignInRCData.DataBean data = response.getData();
                SignInRCData.DataBean.ScoreBean score = data.getScore();
                rule = data.getRule();
                if (score != null) {
                    initUI(data);
                } else {
                    noData.setVisibility(View.VISIBLE);
                    noDataTv.setText(response.getMsg());
                    noDataTv.setVisibility(View.VISIBLE);
                }
            } else {
                noData.setVisibility(View.VISIBLE);
                noDataTv.setText(response.getMsg());
                noDataTv.setVisibility(View.VISIBLE);
            }
        }
    };

    private void initUI(SignInRCData.DataBean data) {
        SignInRCData.DataBean.ScoreBean score = data.getScore();
        if(score.isSigned()==true){
            isSigned = true;
            sign_now.setBackgroundResource(R.mipmap.sign_already);
        }
        totalScore.setText(score.getTotal_left());
        signScore.setText(score.getScore_1());
        consumeScore.setText(score.getScore_5());
        List<SignInRCData.DataBean.LogsBean> logs = data.getLogs();
        if (logs != null && logs.size() > 0) {
            listView.setAdapter(new NestFullListViewAdapter<SignInRCData.DataBean.LogsBean>(R.layout.item_sign_record, logs) {
                @Override
                public void onBind(int position, SignInRCData.DataBean.LogsBean bean, NestFullViewHolder holder) {
                    String amount = bean.getAmount();
                    SpannableString spannableString  = new SpannableString("获得 " + amount + " 积分");
                    SpannableStringBuilder partColor = ObjectUtils.getPartColor(Color.RED, spannableString.toString(), 3, 3 + amount.length());
                    ((TextView) holder.getView(R.id.tv_record_score)).setText(partColor);
                    String strTime = ObjectUtils.getStrTime(bean.getC_time(), "yyyy-MM-dd HH:mm:ss");
                    holder.setText(R.id.tv_record_time, strTime);
                }
            });
        }

    }

    @OnClick({R.id.sign_rule, R.id.sign_now})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sign_rule:
                showRuleDialog();
                break;
            case R.id.sign_now:
                if(!isSigned){
                    toSign();
                }
                break;
        }
    }

    //签到
    private void toSign() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERFSIGNACTION;
        MyLog.e("地址", address);
        if (networkConnected) {
            HttpUtils.post(address, null, signInCallback);
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    private int todayScore;
    SignInDataCallback signInCallback = new SignInDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.toast(mcontext, "签到失败");
        }

        @Override
        public void onResponse(SignInData response, int id) {
            if(response.getCode()==0) {
                todayScore = response.getData().getScore();
//                continue_day = response.getData().getContinue();
                showSuccessDialog();
            }
        }
    };

    private void showRuleDialog() {
        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_signin_rule, null);
        TextView sure = (TextView) v.findViewById(R.id.dialog_sure);
        TextView content = (TextView) v.findViewById(R.id.dialog_content);
        if(rule!=null) {
            content.setText(Html.fromHtml(rule));
        }
        sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialog.dismiss();
                                    }
                                }
        );
        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
    }

    private void showSuccessDialog() {
        successDialog = new AlertDialog.Builder(mcontext).create();
        successDialog.getWindow().setDimAmount(0.5f);//设置昏暗度为0
        successDialog.setCanceledOnTouchOutside(false);
        successDialog.show();

        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_sign_success, null);
        ImageView sure = (ImageView) v.findViewById(R.id.dialog_sure);
        TextView tvTodatScore = (TextView) v.findViewById(R.id.dialog_sign_today_score);
        tvTodatScore.setText("今天已签到，获得" + todayScore + "个积分");
//        TextView tvContinueDay = (TextView) v.findViewById(R.id.dialog_tv_sign_day);
//        SpannableString spannableString  = new SpannableString("获得 " + todayScore + " 积分");
//        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED);
//        spannableString.setSpan(colorSpan, 3, 3+score.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        tvTodatScore.setText(spannableString);
//        tvContinueDay.setText("已连续签到"+continue_day+"天");
        sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        successDialog.dismiss();
                                        getData();
                                    }
                                }
        );
        successDialog.getWindow().setContentView(v);
    }

}
